package com.bjsxt.recommendation.service.impl;

import com.bjsxt.livegoods.pojo.Item;
import com.bjsxt.recommendation.dao.ItemDao;
import com.bjsxt.recommendation.service.RecommendationService;
import com.livegoods.commons.vo.LivegoodsResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @ClassName : ItemService
 * @Description :
 * @Author : ZWZ
 * @Date: 2021/8/23 17:10
 */
@Service
@Slf4j
public class RecommendationServiceImpl implements RecommendationService {

    @Autowired
    private ItemDao itemDao;
    @Value("${livegoods.banner.nginx.prefix}")
    private String nginxPrefix;

    /**
     * 按照 city 和 recommend 查询， 按照 resort 排序
     *
     * @param city
     * @return
     */
    @Override
    public LivegoodsResult getRecommendationItem(String city) {
        try {
            Query query = new Query();
            Criteria criteria = new Criteria();
            criteria.andOperator(
                    Criteria.where("city").is(city),
                    Criteria.where("recommendation").is(true)
            );
            query.addCriteria(criteria);
            query.with(PageRequest.of(0, 4,
                    Sort.by(Sort.Direction.DESC, "recoSort"))
            );
            List<Item> items = itemDao.find(query);
            if (items.size() < 4) {
                Query otherQuery = new Query();
                Criteria otherCriteria = new Criteria();
                otherCriteria.andOperator(
                        Criteria.where("city").ne(city),
                        Criteria.where("recommendation").is(true)
                );
                otherQuery.addCriteria(otherCriteria);
                otherQuery.with(PageRequest.of(0, 4 - items.size(),
                        Sort.by(Sort.Direction.DESC, "recoSort"))
                );
                List<Item> otherItems = itemDao.find(otherQuery);
                items.addAll(otherItems);
            }
            // 查询结果 items，理论上一定有 4 条数据。如果不足？可以使用托底数据填充。
            if (items.size() < 4) {
                for (int i = items.size(); i <= 4; i++) {
                    items.add(fallbackItem());
                }
            }
            // 补充图片路径
            changeImgUrl(items);
            return LivegoodsResult.ok(items);
        } catch (Exception e) {
            log.info("获取 {} 推荐产品失败，错误信息： {}", city, e.getMessage());
            return LivegoodsResult.error(e.getMessage());
        }
    }

    /**
     * 补充图片访问前缀路径
     *
     * @param items
     * @return
     */
    private void changeImgUrl(List<Item> items) {
        items.forEach(item -> {
            item.setImg(nginxPrefix + item.getImg());
            List<String> imgs = item.getImgs();
            List<String> newImgs = new ArrayList<>(imgs.size());
            for (String img : imgs) {
                newImgs.add(nginxPrefix + item.getImg());
            }
            item.setImgs(newImgs);
        });
    }

    /**
     * 托底数据
     *
     * @return
     */
    private Item fallbackItem() {
        Item item = new Item();
        item.setId("5ec1ec6b7f56a946fb7fdffa");
        item.setCity("北京");
        item.setHouseType("150 ㎡");
        item.setImgs(Arrays.asList(
                "group1/M00/00/00/wKiqUGEaZaWAZ4HpABLGyzFLLI0191.png",
                "group1/M00/00/00/wKiqUGEaZrOAJAGzAAuC4z59RTI157.png",
                "group1/M00/00/00/wKiqUGEaZrGAPfbeAAro9zs5IOg948.png")
        );
        item.setPrice(12000L);
        item.setRecommendation(true);
        item.setRecoSort((byte) 9);
        item.setRentType("整租");
        item.setSales(100L);
        item.setTitle("北京高档公寓");
        Map<String, String> info = new HashMap<>();
        info.put("years", "2010");
        info.put("type", "3 室 2 厅");
        info.put("level", "10/18 层");
        info.put("style", "精装修");
        info.put("orientation", "南北通透");
        item.setInfo(info);
        return item;
    }

}
